import axios from 'axios'
import {MessageBox, Message} from 'element-ui'
import store from '@/store'
import {getToken} from '@/utils/auth'
import router from "@/router";

// create an axios instance
const service = axios.create({
    baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
    // withCredentials: true, // send cookies when cross-domain requests
    timeout: 8000, // request timeout
})

// request interceptor
service.interceptors.request.use(
    config => {
        // do something before request is sent

        if (store.getters.token) {
            // 修改全局请求头，满足后端oAuth2认证
            config.headers['authorization'] = 'Bearer ' + getToken()
        }
        return config
    },
    error => {
        // do something with request error
        console.log(error) // for debug
        return Promise.reject(error)
    }
)

// response interceptor
service.interceptors.response.use(
    /**
     * If you want to get http information such as headers or status
     * Please return  response => response
     */

    /**
     * Determine the request status by custom code
     * Here is just an example
     * You can also judge the status by HTTP Status Code
     */
    response => {
        const res = response.data

        // if the custom code is not 20000,
        // 页面解决  -- 100104：用户名已存在   100105：手机号已存在   100200：短信发送异常   100107：手机验证码错误  100110:人脸检测失败
        if (res.code !== 20000 && res.code !== 20001 && res.code !== 100103 && res.code !== 100104 && res.code !== 100105 && res.code !== 100200 && res.code !== 100107 && res.code !== 100110) {
            // 50008: Illegal token; 50010: invalid token; 50012: Other clients logged in; 50014: Token expired;
            if (res.code === 50008 || res.code === 50010 || res.code === 50012 || res.code === 50014) {
                // to re-login
                MessageBox.confirm('您已经登出，您可以取消以停留在此页面，或再次登录', '确认注销', {
                    confirmButtonText: '重新登录',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    store.dispatch('user/resetToken').then(() => {
                        router.push("/login")
                    })
                })
            } else {
                Message({
                    dangerouslyUseHTMLString: true,
                    message: `<strong>${res.message || 'Error'}&nbsp;&nbsp;&nbsp;<i><a href="javascript:;" onclick="return location.reload();">点我刷新</a></i></strong>`,
                    type: 'error',
                    duration: 5000,
                    showClose: true
                })
            }
            // return Promise.reject(new Error(res.message || 'Error'))
            return res
        }
        else {
            return res
        }
    },
    error => {
        console.log('error：' + error) // for debug
        let msg = error.message
        // 当响应异常时做一些处理
        if (error && error.response) {
            switch (error.response.status) {
                // 其他错误，直接抛出错误提示
                case 400:
                    msg = '请求错误(400)';
                    break;
                case 401:
                    msg = '未授权，请重新登录(401)';
                    break;
                case 403:
                    msg = '拒绝访问(403)';
                    break;
                case 404:
                    msg = '请求出错(404)';
                    break;
                case 408:
                    msg = '请求超时(408)';
                    break;
                case 500:
                    msg = '服务器错误(500)';
                    break;
                case 501:
                    msg = '服务未实现(501)';
                    break;
                case 502:
                    msg = '网络错误(502)';
                    break;
                case 503:
                    msg = '服务不可用(503)';
                    break;
                case 504:
                    msg = '网络超时(504)';
                    break;
                case 505:
                    msg = 'HTTP版本不受支持(505)';
                    break;
                default:
                    msg = `连接出错(${error.response.status})!`;
            }
        } else {
            msg = '连接服务器失败！'
        }
        Message({
            dangerouslyUseHTMLString: true,
            message: `<strong>${msg || 'Error'}&nbsp;&nbsp;&nbsp;<i><a href="javascript:;" onclick="return location.reload();">点我刷新</a></i></strong>`,
            type: 'error',
            duration: 5000,
            showClose: true
        })
        return Promise.reject(error)
    }
)

export default service
